import { Button, Checkbox, Empty, Input, message, Spin, notification, Select } from 'antd';
import Cookies from 'js-cookie';
import React, { useCallback, useEffect, useState } from 'react';
import { connect, history } from 'umi';

import ContractModal from '@/pages/OrderManage/ContractModal';
import InvoiceModal from '@/pages/OrderManage/InvoiceModal';
import QMTable from '@/pages/OrderManage/OMTable';
import OrderDetail from '@/pages/OrderManage/OrderDetail';
import { getOrderManageList } from '@/services/orderManage';
import { getErrorMsg } from '@/util/utils';

import styles from './index.less';

const { Search } = Input;
// 选择的开发票id
let selectArr: string[] = [];
// 选择的开发票item
let selectItemArr: any[] = [];
// Contract提示arr
let contractTipsArr: any[] = [];
// isInvoiced提示arr
let invoicedTipsArr: any[] = [];
// 选着的订单总价
let ticketPrice: number = 0;
const { Option } = Select;
function OrderManage() {
  const [title, setTitle] = useState<string>('');
  const [isContractVisible, setIsContractVisible] = useState<boolean>(false);
  const [isInvoiceVisible, setIsInvoiceVisible] = useState<boolean>(false);
  const [list, setList] = useState<any>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchParams, setSearchParams] = useState<any>({
    orderNo: '',
  });

  const [dataDetail, setDataDetail] = useState<any>({});
  const [isOrderDetailVisible, setIsOrderDetailVisible] = useState<boolean>(false);

  const [isInvoiceDisabled, setIsInvoiceDisabled] = useState(false);
  const [isContractDisabled, setIsContractDisabled] = useState(false);

  const getList = useCallback(async () => {
    const res = await getOrderManageList(searchParams);
    const { code, data } = res;
    if (code === 200) {
      const dataCaopy = data.data.map((item: any) => {
        item.isChecked = false;
        return item;
      });
      setList(dataCaopy);
      setLoading(false);
    } else {
      message.error(getErrorMsg(res));
    }
  }, [searchParams]);

  useEffect(() => {
    if (!Cookies.get('saas_token')) {
      return history.push('Login');
    }
    setLoading(true);
    getList().then();
    return () => {
      selectArr.splice(0);
      invoicedTipsArr = [];
      contractTipsArr = [];
      selectItemArr = [];
    };
  }, [searchParams]);

  const onSearch = (value: string) => {
    setSearchParams({
      ...searchParams,
      orderNo: value,
    });
  };

  const handleCheck = (e: any, record: any, itemIndex?: number) => {
    const listCopy = [...list].map((item, idx) => {
      if (idx === itemIndex) {
        item.isChecked = e.target.checked;
      }
      return item;
    });
    setList(listCopy);
    if (e.target.checked) {
      // 新增
      selectArr.push(record.id);
      selectItemArr.push(record);

      const arr1 = selectItemArr.filter((item: any) => {
        return !!item.isInvoiced;
      });
      if (arr1.length>0) {
        setIsInvoiceDisabled(true);
      }else {
        setIsInvoiceDisabled(false);
      }

      const arr2 = selectItemArr.filter((item: any) => {
        return !!item.isContract;
      });
      if (arr2.length>0) {
        setIsContractDisabled(true);
      }else {
        setIsContractDisabled(false);
      }

      ticketPrice = parseFloat(ticketPrice.toString()) + parseFloat((record.paymentAmount).toString());
    } else {
      // 取消
      const index = selectArr.findIndex((item: string) => {
        return item.indexOf(record.id) !== -1;
      });
      selectArr.splice(index, 1);
      selectItemArr.splice(index, 1);

      const arr1 = selectItemArr.filter((item: any) => {
        return !!item.isInvoiced;
      });
      if (arr1.length>0) {
        setIsInvoiceDisabled(true);
      }else {
        setIsInvoiceDisabled(false);
      }

      const arr2 = selectItemArr.filter((item: any) => {
        return !!item.isContract;
      });
      if (arr2.length>0) {
        setIsContractDisabled(true);
      }else {
        setIsContractDisabled(false);
      }

      ticketPrice = parseFloat(ticketPrice.toString()) - parseFloat((record.paymentAmount).toString());
    }
    console.log('SelectArr>>>>', selectArr, ticketPrice, selectItemArr);
  };
  const handleSelectedOrder = (type: number) => {
    if (selectArr.length === 0) {
      return message.warn('请先选择订单');
    }
    // type 1：申请合同 2： 开发票
    if (type === 1) {
      // 申请合同
      for (const i of selectItemArr) {
        if (!!i.isContract) {
          contractTipsArr.push(i);
        }
      }
      if (contractTipsArr.length > 0) {
        notification.open({
          message: '下方订单已完成申请合同，请取消勾选！',
          duration: 3,
          description: <>
            {
              contractTipsArr.map((i: any) => {
                return <div key={i.id}>
                  <div>{i.orderNo}</div>
                </div>;
              })
            }
          </>,
        });
        contractTipsArr = [];
        return;
      }
      setTitle('申请合同');
      setIsContractVisible(true);
    } else if (type === 2) {
      // 开发票
      for (const i of selectItemArr) {
        if (!!i.isInvoiced) {
          invoicedTipsArr.push(i);
        }
      }
      if (invoicedTipsArr.length > 0) {
        notification.open({
          message: '下方订单已完成开发票，请取消勾选！',
          duration: 3,
          description: <>
            {
              invoicedTipsArr.map((i: any) => {
                return <div key={i.id}>
                  <div>{i.orderNo}</div>
                </div>;
              })
            }
          </>,
        });
        invoicedTipsArr = [];
        return;
      }
      setIsInvoiceVisible(true);
    }
  };
  const handleOrderDetail = (record: any) => {
    setIsOrderDetailVisible(true);
    setDataDetail({
      ...dataDetail,
      ...record,
    });
    console.log('handleOrderDetail>>>>>', record);
  };
  // 开发票完成后更新状态
  const handleOkAfter = () => {
    getList();
    selectArr = [];
    invoicedTipsArr = [];
    contractTipsArr = [];
    selectItemArr = [];
    setIsContractDisabled(false);
    setIsInvoiceDisabled(false);
  };

  const filterSelect = (value: string) => {
    if (value==='1') {
      setSearchParams({ orderNo: '', isInvoiced: true });
      return;
    } else if (value==='2') {
      setSearchParams({ orderNo: '', isInvoiced: false });
      return;
    } else if (value==='3') {
      setSearchParams({ orderNo: '', IsContract: true });
      return;
    } else if (value==='4') {
      setSearchParams({ orderNo: '', IsContract: false });
      return;
    } else {
      setSearchParams({ orderNo: '' });
    }
  };
  return (
    <>
      <div className={styles.content}>
        <div className={styles.historyOrder}>
          <div>历史订单</div>
          <div>
            <Select allowClear placeholder={'请选择筛选'} style={{ width: 200 }} onChange={filterSelect}>
              <Option key={0} value="0">全部</Option>
              <Option key={1} value="1">已开具发票</Option>
              <Option key={2} value="2">未开具发票</Option>
              <Option key={3} value="3">已申请合同</Option>
              <Option key={4} value="4">未申请合同</Option>
            </Select>&nbsp;&nbsp;&nbsp;
            <Search allowClear style={{ width: 200 }} placeholder="请输入订单号" onSearch={onSearch}/>
          </div>
        </div>
        <div className={styles.buttons}>
          <div>
            <Button disabled={isContractDisabled} onClick={() => {
              handleSelectedOrder(1);
            }} type={'primary'}>申请合同</Button>
            <Button disabled={isInvoiceDisabled} onClick={() => {
              handleSelectedOrder(2);
            }} style={{ marginLeft: 22 }} type={'primary'}>开具发票</Button>
          </div>
        </div>
        <Spin spinning={loading}>
          <div className={styles.tableInfo}>
            {
              list.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>
            }
            {list?.map((item: any, index: number) => {
              return (
                <div key={item.id} className={styles.tableDes}>
                  <div className={styles.tableDesContent}>
                    {
                      <Checkbox
                        checked={item.isChecked}
                        disabled={item.status === 0 || item.orderType === 3 || item.status === 1 || item.status === 2 || (!!item.isInvoiced && !!item.isContract)}
                        style={{ marginRight: 5 }} onChange={(e) => handleCheck(e, item, index)}/>
                    }
                    <span>订单日期：{item.createTime}</span>
                    <span style={{ marginLeft: 32 }}>订单号：{item.orderNo}</span>
                    <Button type="link" onClick={(): void => {
                      handleOrderDetail(item);
                    }}>订单详情</Button>
                  </div>
                  <QMTable getList={getList} data={item} isIssueOrApply={'申请合同'} openOrSeeTicket={'开具发票'}/>
                </div>
              );
            })}
          </div>
        </Spin>
      </div>
      <OrderDetail
        dataDetail={dataDetail}
        isOrderDetailVisible={isOrderDetailVisible}
        setIsOrderDetailVisible={setIsOrderDetailVisible}
      />
      <InvoiceModal
        handleOkAfter={handleOkAfter}
        ticketPrice={ticketPrice}
        selectKeys={selectArr}
        openOrSeeTicket={'开具发票'}
        isInvoiceVisible={isInvoiceVisible}
        setIsInvoiceVisible={setIsInvoiceVisible}
      />
      <ContractModal
        handleOkAfter={handleOkAfter}
        selectKeys={selectArr}
        title={title}
        isContractVisible={isContractVisible}
        setIsContractVisible={setIsContractVisible}
      />
    </>
  );
}

const mapState = (state: any) => {
  return {
    OrderManage: state.OrderManage,
  };
};
export default connect(mapState)(OrderManage);
